import { ChangeDetectionStrategy, Component, OnInit, EventEmitter } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { OrderService } from '../../service';
import { Observable, Observer } from 'rxjs';
import { ProductVariant } from '../../domain';
import { filter, map, switchMap } from 'rxjs/operators';
import { DialogService } from 'src/app/dialog';
import { ProductVariantDialogComponent } from '../../../shared/components/product-variant-dialog';

@Component({
  selector: 'app-product-container',
  templateUrl: './product-container.component.html',
  styleUrls: ['./product-container.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProductContainerComponent implements OnInit {
  variants$: Observable<ProductVariant[]>;
  selectedIndex = 1;
  constructor(
    private route: ActivatedRoute,
    private service: OrderService,
    private dialogService: DialogService,
    private router: Router
  ) { }

  ngOnInit() {
    const productId$ = this.route.paramMap.pipe(
      filter(params => params.has('productId')),
      map(params => params.get('productId'))
    );
    this.variants$ = productId$.pipe(
      switchMap(productId =>
        this.service.getProductVariantsByProductId(productId)
      )
    )
  }

  handleDirectBuy(variants: ProductVariant[]) {
    console.log(55, variants)
    // 测试 Observable 和 Observer 的关系
    const myObservable: Observable<number> = new Observable((observer) => {
      console.log('Observable 和 Observer:', observer);
      observer.next(1);
      observer.next(2);
      observer.next(3);
      observer.complete();
    });
    
    const myObserver: Observer<number> = {
      next: (val: number) => {
        console.log('next value:', val);
      },
      error: (err: any) => {
        console.error('error:', err);
      },
      complete: () => {
        console.log('myObserver complete')
      }
    }
    myObservable.subscribe(myObserver);
  }

  handleGroupBuy(variants: ProductVariant[]) {
    const top = 40;
    // EventEmitter 就是 Subject
    // Subject 既是 Observable，也可以是 Observer
    // Subject 可以 subscribe；也可以.next(xxx)，来处理Observable发出的下一个值
    // BehaviorSubject 是 Subject 的一种特殊形式，它可以记住最新的值
    const formSubmitted = new EventEmitter();
    formSubmitted.subscribe(ev => {
      console.log(111, ev);
      this.dialogService.saveData(ev);
      this.router.navigate(['/orders', 'confirm']);
    })

    const selected = new EventEmitter();
    selected.subscribe(ev => {
      console.log(222, ev);
      this.selectedIndex = ev;
    })
    this.dialogService.open(ProductVariantDialogComponent, {
      // 如果 key 和 value 是一个名字，直接写就可以
      inputs: {
        variants,
        selectedVariantIndex: this.selectedIndex
      },
      outputs: {
        formSubmitted,
        selected
      },
      position: {
        top: `${top}%`,
        left: '50%',
        width: '100%',
        height: `${100 - top}%`
      }
    });
  }
}